#include <iostream>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>

using namespace std;

int g_val = 10;
void *newthreadrun(void *arg)
{
    int count = 5;
    while (count)
    {
        //cout << "I am new pthread: " << count << " pid:" <<getpid() << "g_val:"<< g_val << endl;
        cout << "I am new pthread: " << "g_val:"<< g_val <<" &g_val:"<< &g_val << endl;

        g_val++;
        sleep(1);
        count--;
    }
    //终止，并且有返回值，让main等待时可以拿到
    pthread_exit((void*)123);
    //return (void*)123;
}

int main()
{
    pthread_t tid;
    pthread_create(&tid, nullptr, newthreadrun, (void*)"pthread-1");


    sleep(1);
    pthread_cancel(tid);
    void* ret = nullptr;
    int count = 5;
    // while(count)
    // {
    //     cout << "I am main pthread: " << "g_val:"<< g_val <<" &g_val:"<< &g_val << endl;
    //     sleep(1);
    //     count--;
    // }
    int n = pthread_join(tid,&ret);
    //ret转int会丢失精度，因为现在所在是64位，void* 8字节 int 4字节   所以把它强转成long long int
    cout << "main pthread quit"<<" n: "<<"main pthread get a ret:"<< (long long int)ret << " n:"<< n <<endl;




    // while (count)
    // {
    //     cout << "I am main pthread: " << count <<  " pid:" << getpid() << " new thread tid: " << tid << endl;
    //     sleep(1);
    //     count--;
    // }
}